package org.forex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.forex.api.web.async.GetAsyncServlet;
import org.forex.api.web.async.AppManager.AppContext;
import org.forex.impl.ws.GetInstruments;
import org.forex.impl.ws.GetInstrumentsHistory;
import org.forex.vo.Instrument;
import org.forex.vo.Instruments;

import com.google.gson.Gson;

@WebServlet(asyncSupported=true,urlPatterns="/test")
public class ForexAIServlet extends GetAsyncServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 8581874115957576106L;

	public Instruments getInstruments() throws MalformedURLException, IOException{
		HttpsURLConnection con=(HttpsURLConnection) new URL("https://api-fxpractice.oanda.com/v1/instruments?accountId=9646994").openConnection();

		con.setConnectTimeout(30000);

		con.addRequestProperty("Authorization", "Bearer 09d809e0c963493c9f6702917fee51df-02a690da64ae9d33946321659e766397");

		BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));

		List<Instrument> instruments=null;

		Gson gson = new Gson();
        Instruments ins=gson.fromJson(in, Instruments.class);
        //Instrument ins=gson.fromJson(in, Instrument.class);
        in.close();

        return ins;
	}

	@Override
	protected void doAsync(AppContext appContext, AsyncContext asyncContext,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		Gson gson = new Gson();

        //System.out.println(ins.getInstruments().get(0).getPip());

        //resp.getWriter().write(gson.toJson(getInstruments()));
		//response.getWriter().write(gson.toJson(new GetInstruments().get()));
		response.getWriter().write(gson.toJson(new GetInstrumentsHistory().get(null)));
	}
}
